#include "DataBuffer.h"
#include <cstddef>

CDataBuffer::CDataBuffer(const std::string& name,A * data,unsigned int length):
    m_dataName(name),m_DataLength(length),m_BufSize(0)
{ 
    std::cout << "ctor" << std::endl;
    if(data != nullptr){
        m_pFoo = new A(*data);
    }else{
        m_pFoo = nullptr;
    }
}

// CDataBuffer::CDataBuffer(const CDataBuffer& db)
// {
//     this->m_dataName = db.m_dataName;
//     this->m_DataLength = db.m_DataLength;
//     this->m_BufSize = db.m_BufSize;
//     if(db.m_pFoo != nullptr){
        
//     }
//     *(this->m_pFoo) = *(db.m_pFoo); 
// }

CDataBuffer::CDataBuffer(const CDataBuffer& db):
    m_dataName(db.m_dataName),m_DataLength(db.m_DataLength)
{
    std::cout << "cp ctor" << std::endl;
    if(db.m_pFoo != nullptr){
        m_pFoo = new A(*db.m_pFoo);
    }else {
        m_pFoo = nullptr;
    }
}


CDataBuffer& CDataBuffer::operator = (const CDataBuffer& db)
{
    std::cout << "cp assignment" << std::endl;
    if(this == &db){
        return *this;
    }

    // copy swap
    // CDataBuffer temp(db);
    // std::swap(m_pFoo,temp.m_pFoo);
    // m_DataLength = temp.m_DataLength;
    // m_dataName = temp.m_dataName;

    m_dataName = db.m_dataName;
    m_DataLength = db.m_DataLength;
    m_BufSize = db.m_BufSize;
    if(db.m_pFoo != nullptr){
        if(m_pFoo != nullptr){
            *(m_pFoo) = *(db.m_pFoo);
        }else{
            m_pFoo = new A(*db.m_pFoo);
        }
    }else{
        delete m_pFoo; // 先释放内存
        m_pFoo = nullptr;
    }
    return *this;
}

CDataBuffer::~CDataBuffer()
{
    delete m_pFoo;
}

CDataBuffer::CDataBuffer(CDataBuffer && db) noexcept
:m_dataName(std::move(db.m_dataName)),m_DataLength(db.m_DataLength)
{
    std::cout << "move ctor" << std::endl;
    m_pFoo = db.m_pFoo;
    db.m_pFoo = nullptr;
}
CDataBuffer& CDataBuffer::operator = (CDataBuffer&& db) noexcept
{
    std::cout << "move assignment" << std::endl;
    delete m_pFoo;
    m_pFoo = db.m_pFoo;
    db.m_pFoo = nullptr;
    return *this;
}

void CDataBuffer::Dump()
{
    std::cout << "--------------" << std::endl;
    std::cout << m_dataName << std::endl;
    std::cout << m_DataLength << std::endl;
    m_pFoo->Dump();
    std::cout << "Obj size: " << sizeof(*this) << std::endl;
    std::cout << "==============" << std::endl;
}